﻿var toggle_state = 1;
var questionCount = 0;

$(document).ready(function () {

    $("#renameSurveyButton").click(function () {
        $('#renameSurveyModal').modal('show');
    });

    $("#renameSurveyDialogButton").click(function () {
        setNewSurveyName();
    });

    addChoiceTextField($("#createNewQuestion").find(".choiceList"));

    $("#saveQuestionButton").click(function () {
        createNewSurveyQuestion($(this).closest("fieldset"));
    });

    $(".addChoiceOption").click(addChoiceHandler);

    $("#monetize").click(function () {
        setMonetized();
    });

    $("#doneEditingButton").click(function () {
        window.location = "../../Home/Index";
    });

    $(".updateQuestionButton").click(updateQuestion);

    // delete question button handler
    $(".deleteQuestionButton").click(deleteQuestion);

    // delete choice button handler
    $(".deleteButton").click(removeChoice);

    registerFormHandlers();

});

function updateQuestion(fieldset) {
    var fieldset = $(this).closest("fieldset");
    var questionData = getQuestionDataFromForm(fieldset);
    var questionText = questionData.Question;

    $.ajax({
        type: 'POST',
        // the controller and method we're posting to
        url: '/Survey/UpdateQuestion/',
        // get the data from the new question form in the correct format for the controller
        data: JSON.stringify(questionData),
        contentType: "application/json; charset=utf-8",
        // now the data is magically posted to the controller. If successful, we do some additional work below
        success: function (data) {
            // update the question link and close the form because question was successfully updated
            var accordionBodyId = $(fieldset).parents("div.accordion-body").attr("id");
            var anchor = $("[name='" + accordionBodyId + "']").find("a");
            updateQuestionLink(questionText, anchor);
            $("#" + accordionBodyId).collapse('hide'); ;
        }
    });
}

function updateQuestionLink(questionText, anchor) {
    if (questionText.length > 50) {
        questionText = questionText.substring(0, 50) + "...";
    }
    $(anchor).text(questionText);
}

function setQuestionCount() {
    // each accordion parent holds the contents of a single question form
    // so we count these to track how many questions are displayed.
    // We append this count to certain ids to ensure uniqueness
    var questionList = $(".accordion-heading");
    questionCount = questionList.length - 1;
}

function deleteQuestion() {
    var fieldset = $(this).closest("fieldset");
    var questionId = fieldset.find(".questionId").val();
    $.ajax({
        type: 'POST',
        url: '/Survey/DeleteQuestion/',
        data: { id: questionId },
        success: function () {
            // now that the data is deleted, remove the question from the view
            var questionBody = fieldset.parents(".accordion-body");
            var Id = questionBody.attr("id");
            var questionHeader = $(".accordion-heading[name='" + Id + "']");
            questionBody.remove();
            questionHeader.remove();
        }
    });
}

function removeChoices(choiceList) {
    var choices = choiceList[0].children;
    var choiceCount = choices.length;
    for (var i = 0; i < choiceCount; i++) {
        var choice = choices[0];
        removeChoice(choice);
    }
}

function removeChoice() {
    var choice = $(this).closest(".choice");
    var choiceList = $(choice).parent(".choiceList");
    var choiceId = $(choice).find(".choiceId").val();
    var choiceCount = choiceList.find(".choice").length;

    // we need at least one empty text field to add choices
    if (choiceCount > 1) {
        $(choice).remove();
    } else if (choiceCount == 1) {
        // reset the input field to the placeholder value
        $(choice).find(".choiceText").val('');
    }
    if (choiceId != 0) {
        deleteChoice(choiceId);
    }
    return false;
}

function deleteChoice(id) {
    $.ajax({
        type: 'POST',
        // the controller and method we're posting to
        url: '/Survey/DeleteChoice/',
        // must order and name post data to match controller method parameter list
        data: { id: id }
    });
}

function addChoiceHandler() {
    var choiceList = $(this).closest(".choices").find(".choiceList");
    addChoiceTextField(choiceList);
    return false;
}

function addChoiceTextField(choiceList) {
    var choiceDiv = document.createElement("div");
    choiceDiv.setAttribute("class", "input-append choice");

    var choiceId = document.createElement("input");
    choiceId.setAttribute("type", "hidden");
    choiceId.setAttribute("class", "choiceId");
    choiceId.setAttribute("value", "0");

    var choiceInput = document.createElement("input");
    choiceInput.setAttribute("placeholder", "Add option text here...");
    choiceInput.setAttribute("type", "text");
    choiceInput.setAttribute("class", "span3 choiceText");

    var deleteButton = createDeleteButton();

    choiceDiv.appendChild(choiceId);
    choiceDiv.appendChild(choiceInput);
    choiceDiv.appendChild(deleteButton);
    choiceList.append($(choiceDiv));

    $(deleteButton).click(removeChoice);
    return false;
}

function createDeleteButton() {
    
    var deleteButton = document.createElement("a");
    deleteButton.setAttribute("href", "#");
    //deleteButton.setAttribute("role", "button");
    deleteButton.setAttribute("class", "btn btn-danger");
    //deleteButton.setAttribute("data-toggle", "modal");
    deleteButton.setAttribute("title", "Remove option");

    var deleteIcon = document.createElement("i");
    deleteIcon.setAttribute("class", "icon-white icon-remove");
    deleteButton.appendChild(deleteIcon);

    return deleteButton;
}

function resetNewQuestionForm() {
    $("#questionTypeField1").prop("checked", true);
    $("#questionField").val("");
    $("#createNewQuestion").find(".choiceList").children("div").remove();
    $("#createNewQuestion").find(".choices").hide();
}

function resetSurveyField() {
    $("#newSurveyNameField").val("");
}

function setNewSurveyName(){
    var name = $('#surveyNameField').val();
    var id = $('#renameId').val();
    $.ajax({
        type: 'POST',
        // the controller and method we're posting to
        url: '/Survey/Rename/',
        // must order and name post data to match controller method parameter list
        data: { id: id, newName: name },
        success: function (data) {
            // the modal dialog will persist so we reset the field
            if (!(data.toString() === "ERROR")) {
                $("#surveyName").text(data);
            }
            //$('#newSurveyNameField').val('');
        }
    });
}

function setMonetized() {
    var btn = document.getElementById('monetize');
    var icon = document.createElement("i");
    icon.setAttribute("class", "icon-gift icon-white");
    icon.setAttribute("id", "gift_icon");

    var btn_spn = document.getElementById('monetize span');
    var name;
    if (toggle_state == 0) {
        btn.setAttribute("class", "btn btn-small btn-info");
        btn.appendChild(icon);
        $('#monetize span').text('Click to monetize ');
        toggle_state = 1;
        name = "False";
    } else {
        toggle_state = 0;
        btn.setAttribute("class", "btn btn-small btn-success");
        btn.removeChild(document.getElementById("gift_icon"));
        $('#monetize span').text('Click to unmonetize');
        name = "True";
    }

    var id = $('#masterSurveyID').val();
    $.ajax({
        type: 'POST',
        // the controller and method we're posting to
        url: '/Survey/SetMonetized/',
        // must order and name post data to match controller method parameter list
        data: { id: id, monetizedVal: name},
        success: function (data) {
            
        }
    });
}

function createNewSurveyQuestion(fieldset) {
    var questionData = getQuestionDataFromForm(fieldset);
    // use ajax to save question data
    $.ajax({
        type: 'POST',
        // the controller and method we're posting to
        url: '/Survey/CreateQuestion/',
        // get the data from the new question form in the correct format for the controller
        data: JSON.stringify(questionData),
        contentType: "application/json; charset=utf-8",
        // now the data is magically posted to the controller. If successful, we do some additional work below
        success: function (data) {
            // close the question form because it has been successfully submitted
            $("#createNewQuestion").collapse("hide");

            // increment the question count before we append the question to the DOM because we append this value to its id
            questionCount++;

            // add the new question to the list
            appendNewQuestion(data);

            // reset the new question form fields etc...
            resetNewQuestionForm();
        }
    });
}

// dynamically creates a question form, populates it, and adds it to the list
function appendNewQuestion(question) {
    var newHTMLElementId = "updateQuestion" + questionCount;
    var questionAccordion = document.getElementById("questionAccordion");
   
    var questionHeadingDiv = document.createElement("div");
    questionHeadingDiv.setAttribute("class", "accordion-heading");
    questionHeadingDiv.setAttribute("name", newHTMLElementId);

    var questionLink = document.createElement("a");
    questionLink.setAttribute("class", "accordion-toggle accordianHover");
    questionLink.setAttribute("data-toggle", "collapse");
    questionLink.setAttribute("data-parent", "#surveyQuestionListAccordion");
    questionLink.setAttribute("href", "#" + newHTMLElementId);

    // set the question text as the header for the question
    var questionText = question.Question;
    if(questionText.length > 50){
        questionText = questionText.substring(0, 50) + "...";
    }
    var questionLinkText = document.createTextNode(questionText);
    questionLink.appendChild(questionLinkText);
    
    var questionBodyDiv = document.createElement("div");
    questionBodyDiv.setAttribute("id", newHTMLElementId);
    questionBodyDiv.setAttribute("class", "accordion-body collapse");

    var questionInnerDiv = document.createElement("div");
    questionInnerDiv.setAttribute("class", "accordion-inner");

    var form = document.createElement("form");
    var fieldset = document.createElement("fieldset");

    var hiddenSurveyId = document.createElement("input");
    hiddenSurveyId.setAttribute("type", "hidden");
    hiddenSurveyId.setAttribute("name", "surveyId");
    hiddenSurveyId.setAttribute("class", "surveyId");
    hiddenSurveyId.setAttribute("value", question.SurveyId);

    var hiddenQuestionId = document.createElement("input");
    hiddenQuestionId.setAttribute("type", "hidden");
    hiddenQuestionId.setAttribute("name", "questionId");
    hiddenQuestionId.setAttribute("class", "questionId");
    hiddenQuestionId.setAttribute("value", question.Id);

    var questionTextDiv = document.createElement("div");
    questionTextDiv.setAttribute("class", "editor-field");

    var questionTextInput = document.createElement("input");
    questionTextInput.setAttribute("type", "text");
    questionTextInput.setAttribute("name", "questionText");
    questionTextInput.setAttribute("class", "questionText");
    questionTextInput.setAttribute("placeholder", "Enter question text here..."); 

    var selectQuestionParagraph = document.createElement("p");
    var boldSelectQuestionHeader = document.createElement("b");
    var selectQuestionHeaderText = document.createTextNode("Select Question Type");
    boldSelectQuestionHeader.appendChild(selectQuestionHeaderText);

    // question type radio buttons
    var questionTypesDiv = document.createElement("div");
    questionTypesDiv.setAttribute("class", "editor-field");

    var questionType1Label = document.createElement("label");
    var label1Text = document.createTextNode("Text Response");

    var questionType1RadioButton = document.createElement("input");
    questionType1RadioButton.setAttribute("type", "radio");
    questionType1RadioButton.setAttribute("class", "radio questionType");
    questionType1RadioButton.setAttribute("name", "questionType");
    questionType1RadioButton.setAttribute("value", "1");
    
    var questionType2Label = document.createElement("label");
    var label2Text = document.createTextNode("Multiple Choice");
    
    var questionType2RadioButton = document.createElement("input");
    questionType2RadioButton.setAttribute("type", "radio");
    questionType2RadioButton.setAttribute("class", "radio questionType");
    questionType2RadioButton.setAttribute("name", "questionType");
    questionType2RadioButton.setAttribute("value", "2");
    
    var questionType3Label = document.createElement("label");
    var label3Text = document.createTextNode("True/False");
    
    var questionType3RadioButton = document.createElement("input");
    questionType3RadioButton.setAttribute("type", "radio");
    questionType3RadioButton.setAttribute("class", "radio questionType");
    questionType3RadioButton.setAttribute("name", "questionType");
    questionType3RadioButton.setAttribute("value", "3");
                                    
    // multiple choice section
    var multiChoiceDiv = document.createElement("div");
    multiChoiceDiv.setAttribute("class", "choices update");
     
    var multiChoiceHeaderParagraph = document.createElement("p");
    var boldMultiChoiceHeader = document.createElement("b");
    var multiChoiceHeaderText = document.createTextNode("Add Multiple Choice Options");
    boldMultiChoiceHeader.appendChild(multiChoiceHeaderText);

    var choiceListDiv = document.createElement("div");
    choiceListDiv.setAttribute("class", "choiceList");

    // create and append choices
    for (var i = 0; i < question.Choices.length; i++) {
        // create the hidden choice Id input
        var choice = question.Choices[i];
        var choiceId = document.createElement("input");
        choiceId.setAttribute("type", "hidden");
        choiceId.setAttribute("class", "choiceId");
        choiceId.setAttribute("value", choice.Id);

        // create the choice text input
        var choiceInput = document.createElement("input");
        choiceInput.setAttribute("class", "span3 choiceText");
        choiceInput.setAttribute("type", "text");
        choiceInput.setAttribute("name", "choiceText");
        choiceInput.setAttribute("placeholder", "Enter choice text here...");
        choiceInput.setAttribute("value", choice.Choice);

        // create delete link for choice text field
        var choiceDeleteButton = document.createElement("a");
        choiceDeleteButton.setAttribute("href", "#");
        choiceDeleteButton.setAttribute("class", "btn btn-danger deleteButton");
        choiceDeleteButton.setAttribute("title", "Remove option");
        var deleteIcon = document.createElement("i");
        deleteIcon.setAttribute("class", "icon-white icon-remove");
        choiceDeleteButton.appendChild(deleteIcon);

        // create the main choice div for elements
        var choiceDiv = document.createElement("div");
        choiceDiv.setAttribute("class", "input-append choice");

        // append the choice elements to the choice div
        choiceDiv.appendChild(choiceId);
        choiceDiv.appendChild(choiceInput);
        choiceDiv.appendChild(choiceDeleteButton);

        // add choice to choice list div
        choiceListDiv.appendChild(choiceDiv);

        $(choiceDeleteButton).click(removeChoice);
    }

    var addChoiceParagraph = document.createElement("p");
    var addChoiceLink = document.createElement("a");
    addChoiceLink.setAttribute("class", "addChoiceOption");
    addChoiceLink.setAttribute("href", "#");
    var addChoiceLinkText = document.createTextNode("Add Next Choice Option");
    addChoiceLink.appendChild(addChoiceLinkText);

    // add update and delete buttons
    var buttonParagraph = document.createElement("p");
    
    var updateButton = document.createElement("button");
    updateButton.setAttribute("class", "btn btn-primary updateQuestionButton");
    updateButton.setAttribute("type", "button");
    var updateButtonText = document.createTextNode("Update");
    updateButton.appendChild(updateButtonText);
    
    var deleteButton = document.createElement("button");
    deleteButton.setAttribute("class", "btn btn-danger deleteQuestionButton");
    deleteButton.setAttribute("type", "button");
    var deleteButtonText = document.createTextNode("Delete");
    deleteButton.appendChild(deleteButtonText);

    var spacer = document.createElement("div");
    spacer.setAttribute("class", "spacer");

    // assemble the question working from the bottom of the tree to the root

    // assemble fieldset and its children
    fieldset.appendChild(hiddenSurveyId);
    fieldset.appendChild(hiddenQuestionId);

    questionTextDiv.appendChild(questionTextInput);
    fieldset.appendChild(questionTextDiv);

    selectQuestionParagraph.appendChild(boldSelectQuestionHeader);
    fieldset.appendChild(selectQuestionParagraph);

    questionType1Label.appendChild(questionType1RadioButton);
    questionType1Label.appendChild(label1Text);
    questionType2Label.appendChild(questionType2RadioButton);
    questionType2Label.appendChild(label2Text);
    questionType3Label.appendChild(questionType3RadioButton);
    questionType3Label.appendChild(label3Text);

    questionTypesDiv.appendChild(questionType1Label);
    questionTypesDiv.appendChild(questionType2Label);
    questionTypesDiv.appendChild(questionType3Label);

    fieldset.appendChild(questionTypesDiv);

    multiChoiceHeaderParagraph.appendChild(boldMultiChoiceHeader);
    addChoiceParagraph.appendChild(addChoiceLink);

    multiChoiceDiv.appendChild(multiChoiceHeaderParagraph);
    multiChoiceDiv.appendChild(choiceListDiv);
    multiChoiceDiv.appendChild(addChoiceLink);

    fieldset.appendChild(multiChoiceDiv);

    buttonParagraph.appendChild(updateButton);
    buttonParagraph.appendChild(spacer);
    buttonParagraph.appendChild(deleteButton);

    fieldset.appendChild(buttonParagraph);

    // assemble the rest of the elements
    form.appendChild(fieldset);
    questionInnerDiv.appendChild(form);
    questionBodyDiv.appendChild(questionInnerDiv);

    questionHeadingDiv.appendChild(questionLink);

    // now add to the page
    questionAccordion.insertBefore(questionBodyDiv, questionAccordion.childNodes[0]);
    questionAccordion.insertBefore(questionHeadingDiv, questionAccordion.childNodes[0]);

    // register handlers with new elements
    $(deleteButton).click(deleteQuestion);
    registerFormHandlers();

    // now that handlers are registered, we can set form elements dependent on them
    var questionDiv = $("#" + newHTMLElementId);
    questionDiv.find("input[name='questionText']").val(question.Question);
    var radioButton = questionDiv.find("input[value='" + question.Type + "']");
    radioButton.attr("checked", "checked");
    radioButton.click();

    $(addChoiceLink).click(addChoiceHandler);

    $(updateButton).click(updateQuestion);
}

function registerFormHandlers() {

    $(".choices").each(function () {
        if ($(this).closest("fieldset").find(":checked").val() != 2) {
            $(this).hide();
        }
    });

//    $(".updateQuestionButton").click(function () {
//        var question = new Object();
//        var fieldsetElements = $(this).closest("fieldset")[0].elements;
//        question.Id = fieldsetElements[0].value;
//        question.Question = fieldsetElements[1].value;
//        var types = $(this).closest("fieldset").find("input[name=questionType]");
//        for (var i = 0; i < types.length; i++) {
//            if (types[i].checked) {
//                question.Type = types[i].value;
//            }
//        }
//        return false;
//    });

    $(".questionType").click(function () {
        var choices = $(this).closest('fieldset').find('.choices');
        var choiceList = choices.find(".choiceList").get();
        if (this.value == 1 || this.value == 3) {
            choices.hide();
            //removeChoices(choiceList);
        } else {
            if (choiceList[0].children.length == 0) {
                addChoiceTextField($(choiceList));
            }
            choices.show();
        }
    });

    
}

function getQuestionDataFromForm(parameterFieldset) {

    var fieldset = parameterFieldset[0];
    var question = new Object();
    question.Id = $(fieldset).find(".questionId").val();
    question.SurveyId = $(fieldset).find('.surveyId').val();
    question.Question = $(fieldset).find('.questionText').val();
    question.Type = $(fieldset).find(":checked").val();

    if (question.Type == 2) {
        var choiceList = $(fieldset).find(".choiceList").children();
        question.Choices = getChoicesFromForm(question.Id, choiceList);
    } 
    return question;
}

function getChoiceFromForm(questionId, choiceDiv) {
    var choice = new Object();
    choice.Id = 0;
    choice.QuestionId = questionId;
    if (questionId > 0) {
        choice.QuestionId = questionId;
        choice.Id = $(choiceDiv).find(".choiceId").val();
    }
    choice.Choice = $(choiceDiv).find(".choiceText").val();
    return choice;
}

function getChoicesFromForm(questionId, choiceList) {
    var choices = [];
    for (var i = 0; i < choiceList.length; i++) {
        choices[i] = getChoiceFromForm(questionId, choiceList[i]);
    }
    return choices;
}

function getQuestionType(){
    var questionType1 = $('#questionTypeField1');
    var questionType2 = $('#questionTypeField2');
    var questionType3 = $('#questionTypeField3');
    if (questionType1.attr("checked") === "checked") {
        return questionType1.val();
    }
    if (questionType2.attr("checked") === "checked") {
        return questionType2.val();
    }
    if (questionType3.attr("checked") === "checked") {
        return questionType3.val();
    }
    return undefined;
}


//delay function and timer taken from: http://hartzer.wordpress.com/2009/09/18/onkeyup-delay-in-javascript/

function delayTimer() {
    var timer;
    return function (fun, time) {
        clearTimeout(timer);
        timer = setTimeout(fun, time);
    };
}
var delayFunction = delayTimer();